//
//  WatchPlayBackViewController.m
//  VHallSDKDemo
//
//  Created by developer_k on 16/4/12.
//  Copyright © 2016年 vhall. All rights reserved.
//

#import "WatchPlayBackViewController.h"
#import <MediaPlayer/MPMoviePlayerController.h>
#import <AVFoundation/AVFoundation.h>
#import "VHallApi.h"
#import "LYPlaybackView.h"
#import "LYVideoNoDataView.h"
#import "LYPlaybackHeadCell.h"
#import "LYPlaybackContentCell.h"
#import "LYPlaybackService.h"
#import "LYPlaybackModel.h"
#import "LYCustomSlider.h"
#import "LYVideoInstance.h"
#import "LYAppDelegate.h"

#define kViewFramePath  @"frame"
static const NSTimeInterval         kNavViewAnimationTime         = 3.0f;
static const NSTimeInterval         kAnimationTime                = 2.0f ;


UIKIT_STATIC_INLINE void ScreenRotateToPortrait(UIInterfaceOrientation orientation) {
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}


@interface WatchPlayBackViewController ()
<
VHallMoviePlayerDelegate,
UITableViewDelegate,
UITableViewDataSource,
RequestDelegate
>

{
    
}

@property(nonatomic,strong) MPMoviePlayerController * hlsMoviePlayer;
@property(nonatomic,strong) VHallMoviePlayer *moviePlayer;
@property (nonatomic,assign) VHallMovieVideoPlayMode playModelTemp;
@property (weak, nonatomic) IBOutlet LYCustomSlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightTimeLabel;
@property(nonatomic,strong) NSTimer *clickTimer;
@property(nonatomic,strong) NSTimer *progressTimer;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property(nonatomic,assign) BOOL isControlViewHidden;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navViewTop;
@property (weak, nonatomic) IBOutlet UIView *overView;
@property(nonatomic,strong) LYPlaybackView *fullOverView;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property(nonatomic,strong) LYVideoNoDataView *noVideoView;
@property(nonatomic,assign) BOOL isError;
@property(nonatomic,strong) LYPlaybackService *playBackService;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,assign) CGFloat sectionViewHeight;
@property(nonatomic,strong) LYPlaybackHeadCell *sectionHeader;
@property(nonatomic,assign) BOOL isFullScreen;
@property(nonatomic,assign) BOOL inThisPage;
@property(nonatomic,strong) UIButton *centerPlayButton;
@property(nonatomic,strong) UIButton *rePlayButton;
@property(nonatomic,strong) LYShareManagerModel *shareManagerModel;
@property (strong, nonatomic) UIImageView *coverImage;
@property(nonatomic,strong) UIButton *backButton;
@property(nonatomic,assign) BOOL isLocked;
@property(nonatomic,assign) BOOL isPressPauseBtn;   //是否点击了暂停按钮

@end

@implementation WatchPlayBackViewController
#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"视频回顾";
    
    [[SensorsAnalyticsSDK sharedInstance] trackTimerBegin:@"VideoReviewWatch"];

    [self _initData];
    [self _initViews];
    [self _initPlayer];
    [self registerLiveNotification];
    NSInteger width = SCREEN_WIDTH;
    
    WS(weakSelf);
    
    if (weakSelf.isVideoLivingPage) {
        return;
    }
    
    [self.playBackService loadPlaybackData:^(BOOL success) {
        if (success) {
            // 如果没有穿roomId进来，就表示播放第一个
            NSArray *roomIdList = [weakSelf.playBackService.mutDataArray valueForKeyPath:@"vurl"];
            if ([LYUtil isNilOrEmpty:weakSelf.playModel.vurl]) {
                LYPlaybackModel *model = weakSelf.playBackService.mutDataArray.firstObject;
                weakSelf.playModel = model;
                NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",weakSelf.playModel.img_url,(long)width];
                [weakSelf.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
                weakSelf.coverImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height);
                [weakSelf _loadShareInfo:model];

            }else{
                NSInteger index = [roomIdList indexOfObject:weakSelf.playModel.vurl];
                if (index>=0 && index< roomIdList.count) {
                    // 存在roomId
                    weakSelf.playModel = [weakSelf.playBackService.mutDataArray objectAtIndex:index];
                    [weakSelf _loadShareInfo:weakSelf.playModel];
                    NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",weakSelf.playModel.img_url,(long)width];
                    [weakSelf.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
                    weakSelf.coverImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height);
                }else{
                    // 不存在roomId
                    LYPlaybackModel *model = weakSelf.playBackService.mutDataArray.firstObject;
                    weakSelf.playModel = model;
                    [weakSelf _loadShareInfo:model];
                    NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",weakSelf.playModel.img_url,(long)width];
                    [weakSelf.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
                    weakSelf.coverImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height);

//                    [LYUtil showFailedHUD:@"您播放的视频不存在" AddedTo:MAIN_WINDOW interval:1.5];
                }
            }
            
            [weakSelf.tableView reloadData];
        }
    }];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!self.isVideoLivingPage) {
        [[LYVideoInstance sharedInstance].moviePlayer stopPlay];
        [[LYVideoInstance sharedInstance].moviePlayer destroyMoivePlayer];
        [LYVideoInstance sharedInstance].moviePlayer = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:kVedioLiveControllerRemoveSmallVideoScreen object:nil];
    }
    [self begainFullScreen];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self _stopClickTimer];
    [self _stopProgressTimer];
   
    [self destoryMoivePlayer];
    [self.hlsMoviePlayer stop];
    self.hlsMoviePlayer = nil;
//
    self.inThisPage = NO;
    
    [[SensorsAnalyticsSDK sharedInstance] track:@"VideoReviewWatch"
                                 withProperties:@{
                                                  @"ly_video_id":[LYUtil lySensorsString:self.playModel.vurl],
                                                  @"ly_video_title":[LYUtil lySensorsString:self.playModel.vtitle],
                                                  @"ly_video_end_time":[LYUtil lySensorsString:[LYUtil returnCurrentTime]],
                                                  }];
    [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:@"VideoReviewWatch"
                                         withProperties:nil];
    
    [self endFullScreen];

}

- (void)pauseWatchPlayBack {
    
    [self.hlsMoviePlayer stop];
}

- (void)startWatchPlayBack:(NSString *)vurl {
    
    [self.coverImage removeFromSuperview];
    LYPlaybackModel *playModel = [LYPlaybackModel new];
    playModel.vurl = vurl;
    self.playModel = playModel;
    [self _startPlayer];
    [self.view addSubview:self.coverImage];
    
    NSInteger width = SCREEN_WIDTH;
    NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",[LYLocalData sharedInstance].roomInfo.offline_img_url,width];
    [self.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
    
    if (self.hlsMoviePlayer.view) {
        [LYUtil showProgressHUDAddedToVideoView:self.hlsMoviePlayer.view];
    }
}

- (void)dealloc
{
    //阻止iOS设备锁屏
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    [self.view removeObserver:self forKeyPath:kViewFramePath];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)destoryMoivePlayer
{
    [_moviePlayer destroyMoivePlayer];
    [self.hlsMoviePlayer stop];
    self.hlsMoviePlayer = nil;
}

#pragma mark - Lifecycle Method
- (id)init
{
    self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil];
    if (self) {
    }
    return self;
}

-(BOOL)shouldAutorotate
{
    if (self.isLocked)  return NO;
    return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (fromInterfaceOrientation == UIDeviceOrientationLandscapeRight || fromInterfaceOrientation == UIDeviceOrientationLandscapeLeft) {
 
    }
}

-(void)viewWillLayoutSubviews
{
    if ([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationPortrait)
        
    {
        _topConstraint.constant = 0;
    }
    else
    {
        _topConstraint.constant = 0;
    }
}

- (void)viewDidLayoutSubviews
{
    _hlsMoviePlayer.view.frame = _backView.bounds;
    [self.backView addSubview:self.hlsMoviePlayer.view];
    [self.backView sendSubviewToBack:self.hlsMoviePlayer.view];
}

#pragma mark ------ private Method
- (void)_moviePlayerViewTap {
    WS(weakSelf)
    if (self.isFullScreen)  return;
    if (!self.isControlViewHidden) {
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.navViewTop.constant = -70;
//            weakSelf.bottomViewBottom.constant = -50;
            weakSelf.bottomView.hidden = YES;
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
        } completion:^(BOOL finished) {
        }];
    } else {
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.navViewTop.constant = 0;
            weakSelf.bottomViewBottom.constant = 0;
            weakSelf.bottomView.hidden = NO;
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
        } completion:^(BOOL finished) {
        }];
    }
    self.isControlViewHidden = !self.isControlViewHidden;
    [self _resetTimer];
}

- (void)_resetTimer {
    if (nil ==_clickTimer) {
        _clickTimer = [NSTimer scheduledTimerWithTimeInterval:kNavViewAnimationTime
                                                       target:self
                                                     selector:@selector(_hideTopView)
                                                     userInfo:nil
                                                      repeats:NO];
        [[NSRunLoop mainRunLoop] addTimer:self.clickTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.clickTimer.fireDate timeIntervalSinceNow]) < kNavViewAnimationTime)
            [self.clickTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kNavViewAnimationTime]];
    }
}

- (void)_stopClickTimer {
    if (self.clickTimer) {
        [self.clickTimer invalidate];
        self.clickTimer = nil;
    }
}

- (void)_hideTopView {
    WS(weakSelf)
    [self _stopClickTimer];
    if (!self.inThisPage)  return;
    [UIView animateWithDuration:kAnimationTime animations:^{
        weakSelf.navViewTop.constant = -70;
//        weakSelf.bottomViewBottom.constant = -50;
        weakSelf.bottomView.hidden = YES;
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    } completion:^(BOOL finished) {
    }];
    self.isControlViewHidden = YES;
}

- (void)_resetProgressTimer {
    if (nil ==_progressTimer) {
        _progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                       target:self
                                                     selector:@selector(_updateProgress)
                                                     userInfo:nil
                                                      repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.progressTimer.fireDate timeIntervalSinceNow]) < 1.0)
            [self.progressTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    }
}

- (void)_stopProgressTimer {
    if (self.progressTimer) {
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
}

- (void)_updateProgress {
    
    NSString *currentTime = [NSString stringWithFormat:@"%f",self.hlsMoviePlayer.currentPlaybackTime];
    NSString *totalTime = [NSString stringWithFormat:@"%f",self.hlsMoviePlayer.duration];
    self.timeLabel.text = [NSString stringWithFormat:@"%@",[self getMMSSFromSS:currentTime]];
    self.rightTimeLabel.text = [self getMMSSFromSS:totalTime];
    self.fullOverView.rightTimeLabel.text = [self getMMSSFromSS:totalTime];
    self.progressSlider.value = self.hlsMoviePlayer.currentPlaybackTime/self.hlsMoviePlayer.duration;
    if (self.fullOverView.fullTimeLabel && self.fullOverView.fullProgressSlider) {
        self.fullOverView.fullTimeLabel.text = [NSString stringWithFormat:@"%@",[self getMMSSFromSS:currentTime]];
        self.fullOverView.fullProgressSlider.value = self.progressSlider.value;
    }
}

-(NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    NSString *format_time;
    if (seconds/3600 == 0) {
        format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    } else {
        format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    }
    return format_time;
}

- (void)_initPlayer {
    
    _moviePlayer = [[VHallMoviePlayer alloc]initWithDelegate:self];
    self.hlsMoviePlayer =[[MPMoviePlayerController alloc] init];
    self.hlsMoviePlayer.controlStyle = MPMovieControlStyleNone;
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer.view setFrame:self.backView.bounds];
    self.hlsMoviePlayer.shouldAutoplay= YES;
   
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_moviePlayerViewTap)];
    self.overView.userInteractionEnabled = YES;
    [self.overView addGestureRecognizer:tap];
  
    //播放器
    _hlsMoviePlayer.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.backView.height);//self.view.bounds;
    [self.backView addSubview:self.hlsMoviePlayer.view];
    [self.backView sendSubviewToBack:self.hlsMoviePlayer.view];
    
}

- (void)_startPlayer {
    
    [_noVideoView removeFromSuperview];

    if (self.hlsMoviePlayer.view) {
        [LYUtil showProgressHUDAddedToVideoView:self.coverImage];
    }
    self.hlsMoviePlayer.view.backgroundColor = [UIColor colorWithHexString:@"#333333"];
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
//    self.playModel.vurl = @"522193684";
    param[@"id"] = self.playModel.vurl;
    param[@"name"] = [UIDevice currentDevice].name;
    param[@"email"] = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [_moviePlayer startPlayback:param moviePlayer:self.hlsMoviePlayer];
    
    [[SensorsAnalyticsSDK sharedInstance] track:@"VideoReviewWatch"
                                 withProperties:@{
                                                  @"ly_video_start_time":[LYUtil lySensorsString:[LYUtil returnCurrentTime]],
                                                  @"ly_video_id":[LYUtil lySensorsString:self.playModel.vurl],
                                                  @"ly_video_title":[LYUtil lySensorsString:self.playModel.vtitle],
                                                  }];
}

- (void)_initData {
    
    self.isControlViewHidden = NO;
    self.isError = NO;
    self.isFullScreen = NO;
    self.inThisPage = YES;   
}

- (void)_initViews {
    
    if (!self.isVideoLivingPage) {
        [self.view addSubview:self.centerPlayButton];
    }
    
    [self.view addSubview:self.rePlayButton];
    [self.view addSubview:self.coverImage];

    //阻止iOS设备锁屏
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    self.progressSlider.layer.cornerRadius = 2.5;
    self.progressSlider.layer.masksToBounds = YES;
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"video_slider"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(_processChange:) forControlEvents:UIControlEventValueChanged];
   
    NSInteger width = SCREEN_WIDTH;
    NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",self.playModel.img_url,width];
    [self.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
    [self.view insertSubview:self.centerPlayButton aboveSubview:self.coverImage];
    [self.view insertSubview:self.navView aboveSubview:self.coverImage];
    self.coverImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height);

    self.centerPlayButton.hidden = NO;
    [self _resetTimer];
}

- (void)_processChange:(UISlider *)slider {
   
    [self.hlsMoviePlayer pause];
    [self.hlsMoviePlayer setCurrentPlaybackTime:(slider.value * self.hlsMoviePlayer.duration)];
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer play];
}


- (void)_handleErrorAction {
    WS(weakSelf)
    self.isError = YES;
    self.rePlayButton.hidden = YES;

    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.hlsMoviePlayer pause];
        if (weakSelf.hlsMoviePlayer.view) {
            [LYUtil hideHUDTo:weakSelf.hlsMoviePlayer.view];
        }
        if (weakSelf.coverImage) {
            [LYUtil hideHUDTo:weakSelf.coverImage];
        }
        weakSelf.coverImage.hidden = YES;
        weakSelf.centerPlayButton.hidden = YES;
        [weakSelf.view addSubview:weakSelf.noVideoView];
        [weakSelf.view insertSubview:weakSelf.noVideoView aboveSubview:weakSelf.overView];
        [weakSelf.view insertSubview:weakSelf.navView aboveSubview:weakSelf.noVideoView];
        weakSelf.noVideoView.frame = weakSelf.hlsMoviePlayer.view.bounds;
        weakSelf.noVideoView.center = weakSelf.hlsMoviePlayer.view.center;
        weakSelf.hlsMoviePlayer.view.backgroundColor = RGB(155, 155, 155);
        if (!weakSelf.isFullScreen) {
            weakSelf.noVideoView.backButton.hidden = NO;
        }
    });
}

//注册通知
- (void)registerLiveNotification
{
    
    [self.view addObserver:self forKeyPath:kViewFramePath options:NSKeyValueObservingOptionNew context:nil];
    //已经进入活跃状态的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive)name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground)name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.hlsMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.hlsMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayeExitFullScreen:) name:MPMoviePlayerDidExitFullscreenNotification object:self.hlsMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_orientationChanged) name:@"UIDeviceOrientationDidChangeNotification"object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.hlsMoviePlayer];
}

#pragma mark - 返回上层界面
- (IBAction)closeBtnClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    [self destoryMoivePlayer];
    [self.hlsMoviePlayer stop];
    self.hlsMoviePlayer = nil;
}

- (void)backAction {

    [self closeBtnClick:nil];
}

#pragma mark ------ event Response
- (void)playVideo {

    if (!self.isPressPauseBtn) {
        [self _startPlayer];
    }
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer play];

}

- (void)replayVideo {

    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer play];
    self.fullOverView.original = 0;

}

- (IBAction)shareAction:(id)sender {
    
    WS(weakSelf)
    
    if (self.isVideoLivingPage) {
        !self.VideoLivingPageShareBlock?:self.VideoLivingPageShareBlock();
        return;
    }
    
    [LYShareManager showWithShareModel:self.shareManagerModel callback:^(BOOL shareSuccess, LYShareManagerModel *sharedModel, id result) {
        
        if (shareSuccess) {
            NSString *shareTypeStr = nil;
            if (sharedModel.channel == LYShareWeixiSession) {
                shareTypeStr = @"微信";
            } else if (sharedModel.channel == LYShareWeixiTimeline) {
                shareTypeStr = @"朋友圈";
            } else if (sharedModel.channel == LYShareQQSpace) {
                shareTypeStr = @"QQ空间";
            } else if (sharedModel.channel == LYShareQQ) {
                shareTypeStr = @"QQ";
            } else if (sharedModel.channel == LYSinaWeibo) {
                shareTypeStr = @"微博";
            }
            [[SensorsAnalyticsSDK sharedInstance] track:@"VideoReviewForward"
                                         withProperties:@{
                                                          @"ly_forward_type":[LYUtil lySensorsString:shareTypeStr],
                                                          @"ly_video_id":[LYUtil lySensorsString:weakSelf.playModel.vurl],
                                                          @"ly_video_title":[LYUtil lySensorsString:weakSelf.playModel.vtitle],
                                                          }];
            [LYUtil showSuccessHUD:@"分享成功！" AddedTo:MAIN_WINDOW interval:1.5];
        }
    }];
}

- (IBAction)toFullViewAction:(id)sender {
    ScreenRotateToPortrait(UIInterfaceOrientationLandscapeRight);
}

- (IBAction)playVideoAction:(UIButton *)button {
    
    if (button.selected) {
        [self.hlsMoviePlayer prepareToPlay];
        [self.hlsMoviePlayer play];
        self.isPressPauseBtn = NO;
    } else {
        [self.hlsMoviePlayer pause];
        self.isPressPauseBtn = YES;
    }
}

- (void)_loadShareInfo:(LYPlaybackModel *)model {

    self.shareManagerModel.shareTitle = model.vtitle;;
    self.shareManagerModel.shareContent = model.vcontent;
    self.shareManagerModel.shareImageUrl = model.img_url;
    self.shareManagerModel.shareUrl = model.link_url;
    self.shareManagerModel.shareType = LYShareText;
    self.fullOverView.currentPlayModel = model;
}

- (void)_orientationChanged {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortrait:{
            if (!self.isLocked) {
                [self _toSmallScreen];
            }
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:{
            [self setNeedsStatusBarAppearanceUpdate];
            if (!self.isLocked) {
                [self _toFullScreen];
            }
        }
            break;
        default:
            break;
    }
}

- (void)_toSmallScreen {
    WS(weakSelf);
    self.backButton.hidden = NO;
    self.fullOverView.alpha = 0;
    self.isFullScreen = NO;
    self.centerPlayButton.center = CGPointMake(self.overView.centerX,self.overView.centerY);
    self.rePlayButton.center = CGPointMake(self.overView.centerX,self.overView.centerY);
    self.coverImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height);
    [self.fullOverView removeFromSuperview];
    if (self.hlsMoviePlayer.playbackState == MPMoviePlaybackStatePaused) {
        self.playButton.selected = YES;
    } else {
        self.playButton.selected = NO;
    }
    self.isControlViewHidden = YES;
    [self _moviePlayerViewTap];
    
    if (self.isError) {
        weakSelf.noVideoView.backButton.hidden = NO;
        [weakSelf.view addSubview:weakSelf.noVideoView];
        [weakSelf.view insertSubview:weakSelf.noVideoView aboveSubview:weakSelf.overView];
        [weakSelf.view insertSubview:weakSelf.navView aboveSubview:weakSelf.noVideoView];
        weakSelf.noVideoView.frame = weakSelf.hlsMoviePlayer.view.bounds;
        weakSelf.noVideoView.center = weakSelf.hlsMoviePlayer.view.center;
        weakSelf.hlsMoviePlayer.view.backgroundColor = RGB(155, 155, 155);
    } else {
        weakSelf.noVideoView.backButton.hidden = YES;
    }    
}

- (void)_toFullScreen {
    WS(weakSelf);
    self.isLocked = NO;
    self.backButton.hidden = YES;
    self.fullOverView.alpha = 1;
    self.isFullScreen = YES;
    [self.view addSubview:self.fullOverView];
    self.centerPlayButton.center = CGPointMake(self.overView.centerX,self.overView.centerY);
    self.rePlayButton.center = CGPointMake(self.overView.centerX,self.overView.centerY);
    [self.view insertSubview:self.centerPlayButton aboveSubview:self.fullOverView];
    [self.view insertSubview:self.rePlayButton aboveSubview:self.fullOverView];

    self.fullOverView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.coverImage.frame = self.fullOverView.frame;
    if (self.hlsMoviePlayer.playbackState == MPMoviePlaybackStatePaused) {
        self.fullOverView.playButton.selected = YES;
    } else {
        self.fullOverView.playButton.selected = NO;
    }
    [self _hideTopView];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    if (self.isError) {
        weakSelf.noVideoView.backButton.hidden = YES;
        [weakSelf.view addSubview:weakSelf.noVideoView];
        [weakSelf.view insertSubview:weakSelf.noVideoView aboveSubview:weakSelf.overView];
        weakSelf.noVideoView.frame = weakSelf.hlsMoviePlayer.view.bounds;
        weakSelf.noVideoView.center = weakSelf.hlsMoviePlayer.view.center;
        weakSelf.hlsMoviePlayer.view.backgroundColor = RGB(155, 155, 155);
    }
}

//进入全屏
-(void)begainFullScreen
{
    LYAppDelegate *appDelegate = (LYAppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    LYAppDelegate *appDelegate = (LYAppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    
    //强制归正：
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

#pragma mark - RequestDelegate
-(void) eventRequestSuccess:(id)obj{
    
    [LYUtil hideHUDTo:self.view];
}

-(void) eventRequestError:(id)obj{
    
    [LYUtil hideHUDTo:self.view];
}

-(void) eventRequestBegining:(id)obj{
    
    [LYUtil showProgressHUDAddedTo:self.view];
}


#pragma mark ------ UITableViewDataSource && Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    WS(weakSelf);
    if (section == 0) {
        LYPlaybackHeadCell *cell = [LYPlaybackHeadCell cellWithTableView:tableView];
        self.sectionHeader = cell;
        if (self.playBackService.mutDataArray.count) {
            LYPlaybackModel *model = nil;
            for (LYPlaybackModel *playModel in self.playBackService.mutDataArray) {
                if ([playModel.vurl isEqualToString:self.playModel.vurl]) {
                    model = playModel;
                }
            }
            cell.model = model;
        }
        cell.arrowBlock = ^(CGFloat height) {
            weakSelf.sectionViewHeight = height;
            [weakSelf.tableView reloadData];
        };
        return cell;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.playBackService.mutDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LYPlaybackContentCell *cell = [LYPlaybackContentCell cellWithTableView:tableView];
    [cell normalCellState];
       if (self.playBackService.mutDataArray.count) {
            LYPlaybackModel *model = self.playBackService.mutDataArray[indexPath.row];
            cell.model = model;
            if ([model.vurl isEqualToString:self.playModel.vurl]) {
                [cell selectCellState];
            }
        }
        return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (self.playBackService.mutDataArray.count) {
        for (LYPlaybackModel *playModel in self.playBackService.mutDataArray) {
            if ([playModel.vurl isEqualToString:self.playModel.vurl] && playModel.isOpen == NO) {
            self.sectionViewHeight = [LYUtil sizeWithText:playModel.vtitle font:[UIFont fontWithName:@"PingFangSC-Regular" size:15.0f] withWidth:SCREEN_WIDTH - 20].height + 80;
            }
        }
    }
    return self.sectionViewHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LYPlaybackModel *model = self.playBackService.mutDataArray[indexPath.row];
    // 点击同一行不处理
    if ([model.vurl isEqualToString:self.playModel.vurl]) {
        return;
    }
    self.playModel = model;
    self.coverImage.hidden = NO;
    NSInteger width = SCREEN_WIDTH;
    NSString *imgUrl = [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",model.img_url,width];
    [self.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
    [self _startPlayer];
    [self _loadShareInfo:model];
    [self.playBackService.mutDataArray enumerateObjectsUsingBlock:^(LYPlaybackModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        model.isOpen = NO;
    }];
    [tableView reloadData];
    for (LYPlaybackContentCell *cell in tableView.visibleCells) {
        [cell normalCellState];
    }
    LYPlaybackContentCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell selectCellState];
    _rePlayButton.hidden = YES;
}


#pragma mark - VHMoviePlayerDelegate
- (void)playError:(LivePlayErrorType)livePlayErrorType info:(NSDictionary *)info;
{
    if (self.hlsMoviePlayer.view) {
        [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
    }
    NSString * msg = @"";
    switch (livePlayErrorType) {
        case kLivePlayParamError:
        {
            msg = @"参数错误";
            LYLog(@"%@",msg);
            [self _handleErrorAction];
        }
            break;
        case kLivePlayRecvError:
        {
            msg = @"对方已经停止直播";
            LYLog(@"%@",msg);
            [self _handleErrorAction];

        }
            break;
        case kLivePlayCDNConnectError:
        {
            msg = @"服务器任性...连接失败";
            LYLog(@"%@",msg);
            [self _handleErrorAction];

        }
            break;
        case kLivePlayGetUrlError:
        {
            msg = @"获取服务器地址报错";
            LYLog(@"%@",info[@"content"]);
            [self _handleErrorAction];

        }
            break;
        default:
            break;
    }
}

-(void)VideoPlayMode:(VHallMovieVideoPlayMode)playMode isVrVideo:(BOOL)isVrVideo
{
    LYLog(@"---%ld",(long)playMode);
    self.playModelTemp = playMode;
    
    switch (playMode) {
        case VHallMovieVideoPlayModeNone:
        case VHallMovieVideoPlayModeMedia:
            
            break;
        case VHallMovieVideoPlayModeTextAndVoice:
        {
        }
            
            break;
            
        case VHallMovieVideoPlayModeTextAndMedia:
            
            break;
        default:
            break;
    }
}

-(void)ActiveState:(VHallMovieActiveState)activeState
{
    LYLog(@"activeState-%ld",(long)activeState);
}

#pragma mark - ObserveValueForKeyPath
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:kViewFramePath])
    {
        _hlsMoviePlayer.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.backView.height);
        [self.backView sendSubviewToBack:self.hlsMoviePlayer.view];
    }
}

- (void)moviePlaybackStateDidChange:(NSNotification *)note
{
    switch (self.hlsMoviePlayer.playbackState)
    {
        case MPMoviePlaybackStatePlaying:
        {
            LYLog(@"播放");
            self.centerPlayButton.hidden = YES;
            self.playButton.selected = NO;
            self.fullOverView.playButton.selected = NO;
            self.rePlayButton.hidden = YES;
            if (self.playModelTemp == VHallMovieVideoPlayModeTextAndVoice ) {}
        }
            break;
        case MPMoviePlaybackStateSeekingBackward:
        case MPMoviePlaybackStateSeekingForward:
        {
            LYLog(@"快进－－快退");
        }
            break;
        case MPMoviePlaybackStateInterrupted:
        {
            LYLog(@"中断了");
        }
            break;
        case MPMoviePlaybackStatePaused:
        {
            LYLog(@"暂停");
            self.centerPlayButton.hidden = NO;
            self.rePlayButton.hidden = YES;
            self.playButton.selected = YES;
            self.fullOverView.playButton.selected = YES;

            if (self.hlsMoviePlayer.view) {
                [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
            }
            if (self.playModelTemp == VHallMovieVideoPlayModeTextAndVoice ) { }
        }
            break;
        case MPMoviePlaybackStateStopped:
        {
            LYLog(@"停止播放");
            if (self.hlsMoviePlayer.view) {
                [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
            }
            if (self.playModelTemp == VHallMovieVideoPlayModeTextAndVoice ) { }
        }
            break;
        default:
            break;
    }
}

- (void)movieLoadStateDidChange:(NSNotification *)note
{
    if (self.hlsMoviePlayer.loadState == MPMovieLoadStatePlayable)
    {
        if (self.hlsMoviePlayer.view) {
            [LYUtil showProgressHUDAddedToVideoView:self.hlsMoviePlayer.view];
        }
        LYLog(@"开始加载加载");
    }else if(self.hlsMoviePlayer.loadState == (MPMovieLoadStatePlaythroughOK|MPMovieLoadStatePlayable))
    {
        if (self.hlsMoviePlayer.view) {
            [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
        }
        self.coverImage.hidden = YES;
        self.isError = NO;
        [self.noVideoView removeFromSuperview];
        LYLog(@"加载完成");
        [self _resetProgressTimer];
        self.playButton.selected = NO;
        self.centerPlayButton.hidden = YES;
    }
}

-(void)moviePlayeExitFullScreen:(NSNotification*)note
{
    
}

- (void)moviePlaybackDidFinish:(NSNotification *)note {
    
    [self _stopProgressTimer];
    self.progressSlider.value = 0;
    self.fullOverView.fullProgressSlider.value = 0;
    self.playButton.selected = YES;
    self.rePlayButton.hidden = NO;
    self.centerPlayButton.hidden = YES;
    self.rePlayButton.center = CGPointMake(self.overView.centerX,self.overView.centerY);
    LYLog(@"播放完成");
   
    [[SensorsAnalyticsSDK sharedInstance] track:@"VideoReviewWatch"
                                 withProperties:@{
                                                  @"ly_video_id":[LYUtil lySensorsString:self.playModel.vurl],
                                                  @"ly_video_title":[LYUtil lySensorsString:self.playModel.vtitle],
                                                  @"ly_video_end_time":[LYUtil lySensorsString:[LYUtil returnCurrentTime]],
                                                  }];
}

- (void)didEnterBackground {

    LYLog(@"watchPlayBack ==================================================================================== didEnterBackground")
    
    [self.hlsMoviePlayer pause];
    self.playButton.selected = YES;

}

- (void)didBecomeActive
{
    
    LYLog(@"watchPlayBack ==================================================================================== didBecomeActive")
    
    //观看直播
//    [self.hlsMoviePlayer prepareToPlay];
//    [self.hlsMoviePlayer play];         
//    self.playButton.selected = NO;
}

#pragma mark ----- getters and setters
- (LYPlaybackView *)fullOverView {
    
    WS(weakSelf);
    if (nil == _fullOverView) {
        _fullOverView = [LYPlaybackView viewWithXib];
        _fullOverView.backBlock = ^{
            ScreenRotateToPortrait(UIInterfaceOrientationPortrait);
            [weakSelf _toSmallScreen];
        };
        _fullOverView.block = ^(BOOL play) {
            if (play) {
                [weakSelf.hlsMoviePlayer prepareToPlay];
                [weakSelf.hlsMoviePlayer play];
            } else {
                [weakSelf.hlsMoviePlayer pause];
            }
        };
        _fullOverView.lockBlock = ^(BOOL action) {
            weakSelf.isLocked = action;
        };
        _fullOverView.voiceBlock      = ^(CGFloat value)                   { [VHallMoviePlayer setSysVolumeSize:value];     };
        _fullOverView.processValue = ^(CGFloat value) {
            [weakSelf.hlsMoviePlayer pause];
            [weakSelf.hlsMoviePlayer setCurrentPlaybackTime:(value * weakSelf.hlsMoviePlayer.duration)];
            [weakSelf.hlsMoviePlayer prepareToPlay];
            [weakSelf.hlsMoviePlayer play];
          
            NSString *currentTime = [NSString stringWithFormat:@"%f",weakSelf.hlsMoviePlayer.currentPlaybackTime];
            NSString *totalTime = [NSString stringWithFormat:@"%f",weakSelf.hlsMoviePlayer.duration];
            weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@",[weakSelf getMMSSFromSS:currentTime]];
            weakSelf.rightTimeLabel.text = [weakSelf getMMSSFromSS:totalTime];
            weakSelf.fullOverView.rightTimeLabel.text = [weakSelf getMMSSFromSS:totalTime];
            if (weakSelf.fullOverView.fullTimeLabel && weakSelf.fullOverView.fullProgressSlider) {
                weakSelf.fullOverView.fullTimeLabel.text = [NSString stringWithFormat:@"%@",[weakSelf getMMSSFromSS:currentTime]];
            }
        };
        _fullOverView.isVideoLivingPage = self.isVideoLivingPage;
    }
    return _fullOverView;
}

- (LYVideoNoDataView *)noVideoView {
    WS(weakSelf)
    if (nil == _noVideoView) {
        _noVideoView = [LYVideoNoDataView viewWithXib];
        _noVideoView.refreshBlock = ^() {
            [weakSelf _startPlayer];
            [weakSelf.noVideoView removeFromSuperview];
        };
        
        _noVideoView.backBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _noVideoView;
}

- (LYPlaybackService *)playBackService {

    if (nil == _playBackService) {
        _playBackService = [[LYPlaybackService alloc] initWithDelegate:self];
    }
    return _playBackService;
}

- (UIButton *)centerPlayButton {

    if (self.isVideoLivingPage) {
        return nil;
    }
    
    if (nil == _centerPlayButton) {
        _centerPlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _centerPlayButton.frame = CGRectMake(SCREEN_WIDTH/2- 25,self.backView.size.height/2-25 , 50, 50);
        [_centerPlayButton setImage:[UIImage imageNamed:@"playblack_centerPlay"] forState:UIControlStateNormal];
        _centerPlayButton.hidden = YES;
        [_centerPlayButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _centerPlayButton;
}

- (UIButton *)rePlayButton {

    if (self.isVideoLivingPage) {
        return nil;
    }

    if (nil == _rePlayButton) {
        _rePlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rePlayButton.frame = CGRectMake(self.hlsMoviePlayer.view.centerX, self.hlsMoviePlayer.view.centerY, 56, 72);
        [_rePlayButton setImage:[UIImage imageNamed:@"playblack_replay"] forState:UIControlStateNormal];
        [_rePlayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _rePlayButton.hidden = YES;
        [_rePlayButton addTarget:self action:@selector(replayVideo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rePlayButton;
}

- (LYShareManagerModel *)shareManagerModel {

    if (nil == _shareManagerModel) {
        _shareManagerModel = [LYShareManagerModel new];
    }
    return _shareManagerModel;
}

- (UIImageView *)coverImage {

    if (nil == _coverImage) {
        _coverImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.backView.height)];
        _coverImage.backgroundColor = RGB(155, 155, 155);
        _coverImage.contentMode = UIViewContentModeScaleAspectFill;
        _coverImage.clipsToBounds = YES;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(10, 30, 40, 40);
        [button setImage:[UIImage imageNamed:@"video_full_back"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        [_coverImage addSubview:button];
        self.backButton = button;
    }
    return _coverImage;
}

@end
